
_ = require 'underscore'
certificate = require '../db/Certificate'
fsp = require '../bin/libs/fs-promises'
Q = require 'q'
file = require '../db/File'

###
  证书管理
  ###

module.exports = (app) ->

    certificate_path = app.get('certificate_path')

    app.get '/certificate', (req, res, next) ->
      res.render 'customize', title: 'customize'

    #查询所有证书
    app.get '/certificates', (req, res, next) ->
      certificate.findAll (err, data) ->
         return res.status(404).json {code:-1, message:'Can\'t find certificates.'} if err
         res.status(200).json {code: 0, data: data}

    #分页查询证书
    app.get '/certificates/:page/:limit', (req, res, next) ->
      keyword = req.query.keyword || ""
      page = 1
      limit= 10
      query_obj = if req.query.name then {name: new RegExp(req.query.name)} else {}
      new Promise (resolve, reject) ->
        page = +req.params.page
        limit = +req.params.limit
        certificate.count query_obj, (err, count) ->
           return reject(err) if err
           resolve(count)
      .then (count) ->
        new Promise (resolve, reject) ->
          #按照name 模糊查询
          certificate.list page, limit, keyword, query_obj, (err, data) ->
             return reject(err) if err
             res.status(200).json {code:0, data: data, total: count}
      .catch (err) ->
        return res.status(404).json {code:-1, message:'Can\'t find certificates.'}

    #查询证书 by id
    app.get '/certificates/:certificate_id', (req, res, next) ->
      certificate.findOne _id: req.params.certificate_id, (err, data) ->
         return res.status(404).json {code:-1, message:'Can\'t find certificates.'} if err
         res.status(200).json {code: 0, data: data}

    #删除证书 by id
    #删除文件－删除关联文件表数据－删除该表纪录
    app.delete '/certificates/:certificate_id', (req, res, next) ->
      dir_path = "#{certificate_path}#{req.params.certificate_id}"
      new Promise (resolve, reject) ->
        fsp.remove dir_path
        .then ->
          resolve()
        .catch (err) ->
          return reject(err) if err
      .then ->
        new Promise (resolve, reject) ->
          file.remove owner_id: req.params.certificate_id, (err, result) ->
            return reject(err) if err
            resolve result
      .then () ->
        new Promise (resolve, reject) ->
          certificate.findOneAndRemove _id: req.params.certificate_id, (err, obj) ->
            return reject(err) if err
            resolve(obj)
      .then (data) ->
        res.status(200).json {code: 0, data: 'delete successfully'}
      .catch (err) ->
        console.log err
        res.status(404).json {code:-1, message:'delete Failed'}

    #更新证书 by id
    app.put '/certificates/:certificate_id', (req, res, next) ->
      update =  _.pick(req.body, ['name', 'type', 'password', 'description'])
      certificate.findOneAndUpdate _id: req.params.certificate_id, update, (err, data) ->
         return res.status(404).json {code:-1, message:'Can\'t find certificates.'} if err
         res.status(200).json {code: 0, data: 'update successfully'}

    # 增加证书
    app.post '/certificates', (req, res, next) ->
      _certificate = _.pick(req.body, ['name', 'type', 'password', 'description'])
      new Promise (resolve, reject) ->
        certificate.save _certificate, (err, obj) ->
          return reject(err) if err
          resolve(obj)
      .then (obj) ->
        new Promise (resolve, reject) ->
          Q.all [
            fsp.ensureDir "#{certificate_path}#{obj.id}/"
          ]
          .then ->
            resolve(obj)
          .catch (err) ->
            return reject(err) if err
      .then (data) ->
        res.status(200).json({code: 0, msg: "successfully", data: data})
      .catch (err) ->
        console.log err
        res.status(404).json {code:-1, message:'add Failed'}
